from sqlalchemy import *
from sqlalchemy.orm import *

__all__ = ['metadata', 'session', 'bind', 'create_tables', 'drop_tables', 'get_test_engine']

Session = scoped_session(sessionmaker(autoflush=False, autocommit=True))
metadata = ThreadLocalMetaData()
session = None

def bind(engine):
    """Bind the given sqlalchemy engine to the metadata and session."""
    global session, metadata
    if session is None:
        session = Session(bind=engine) # autocommit? autoflush?
    if metadata.bind is None:
        metadata.bind = engine

def create_tables():
    """Create all tables attached to metadata."""
    global metadata
    metadata.create_all()
    
def drop_tables():
    """Drop all tables attached to metadata."""
    global metadata
    metadata.drop_all()

def get_test_engine():
    """Return a sqlite in-memory sqlalchemy engine for testing purposes"""
    return create_engine('sqlite:///:memory:', echo=True, strategy='threadlocal')